using UnityEngine;
using System;

[AddComponentMenu("TagMachine/GEntity/AI Wanderer")]
public class AIWanderer : MonoBehaviour
{
    public float WanderDistance 	= 20.0f;
    public float WanderRate 		= 2.0f;

	public float ChangeDestinationDistance = 1.0f;
    public float StopMovingDuration = 2.0f;
    public int NumDestinationBeforeStopMin = 2;
    public int NumDestinationBeforeStopMax = 6;
    private int m_CurrentNumDestinationBeforeStop = 0;

	private NavMeshAgent m_AIAgent 	= null;

    private Timer m_StopMovingTimer = null;
	private bool m_StopMoving 		= false;

	void Awake()
	{
		m_AIAgent = GetComponent< NavMeshAgent >();

		if ( m_AIAgent == null )
		{
			Debug.LogWarning("No NavMeshAgent found on " + this);
			Destroy( this );
			return;
		}

		// Create timer
		m_StopMovingTimer 				= gameObject.AddComponent< Timer >();
		m_StopMovingTimer.StartOnAwake 	= false;
		m_StopMovingTimer.DestroyOnEnd 	= false;
		m_StopMovingTimer.RestartTimes	= 1;
		m_StopMovingTimer.TimerCallbackEvent += ToggleStopMoving;

		m_CurrentNumDestinationBeforeStop = 
			UnityEngine.Random.Range( NumDestinationBeforeStopMin, NumDestinationBeforeStopMax );

		ChangeDirection();
	}

	void Update()
	{
		if ( !m_StopMoving && m_AIAgent.remainingDistance <= ChangeDestinationDistance )
		{
			--m_CurrentNumDestinationBeforeStop;
			if ( m_CurrentNumDestinationBeforeStop <= 0)
			{
				ToggleStopMoving();
			}
			else
			{
				ChangeDirection();
			}
		}
	}

    void ChangeDirection()
    {
    	if ( !m_StopMoving )
    	{
    		Vector3 Direction;
    		do
    		{
		        // point in a new random direction and then multiply that by the wander distance
		        Direction = transform.position +
		        	transform.forward * WanderDistance +
		        	UnityEngine.Random.insideUnitSphere * WanderRate;
		    }
	        while ( !m_AIAgent.SetDestination( Direction ) );
	    }
    }

    void ToggleStopMoving()
    {
    	m_StopMoving = !m_StopMoving;

		if ( m_StopMoving )
		{
			m_AIAgent.Stop();
			m_StopMovingTimer.Duration 	= UnityEngine.Random.Range( 0.0f, StopMovingDuration );
			m_StopMovingTimer.Restart();
		}
		else
		{
			m_CurrentNumDestinationBeforeStop = 
				UnityEngine.Random.Range( NumDestinationBeforeStopMin, NumDestinationBeforeStopMax );
			ChangeDirection();
		}
    }

    void OnDrawGizmosSelected()
    {
    	if ( m_AIAgent != null && m_AIAgent.hasPath )
    	{
			// Display the explosion radius when selected
			Gizmos.color = Color.yellow;
			Gizmos.DrawSphere( m_AIAgent.destination, 0.2f );
		}
	}
}